const localSqliteApi = function(DBname = 'main', table_name = 'table1') {
	return {
		// 查询列表
		getList: (params) => new Promise((resolve, reject) => {
			let sql
			if (params) {
				sql = `select * from ${table_name} WHERE `
				Object.keys(params).forEach(function(key) {
					sql = sql + key + '=' + "'" + params[key] + "'" + ' AND'
				})
				sql = sql.substring(0, sql.length - 4); // 去掉最后一个'AND'
			} else {
				sql = `select * from ${table_name}`
			}
			plus.sqlite.selectSql({
				name: DBname,
				sql: sql,
				success: function(data) {
					console.log(`select ${table_name} success: `);
					resolve(data)
					// for (var i in data) {
					// 	console.log(data[i]);
					// }
				},
				fail: function(e) {
					console.log('select table1 failed: ' + JSON.stringify(e));
					reject(e); //失败回调
				}
			})
		}),

		// 查询单一
		getItem: (id) => new Promise((resolve, rejece) => {
			plus.sqlite.selectSql({
				name: DBname,
				sql: `select * from ${table_name} where id=${id}`,
				success: function(data) {
					console.log(`select ${table_name} success: `);
					console.log(data[0])
					resolve(data[0])
				},
				fail: function(e) {
					console.log(`select ${table_name} failed: ` + JSON.stringify(e));
					reject(e); //失败回调
				}
			})
		}),

		// 更新
		update: (params) => new Promise((resolve, reject) => {
			let setFields = ''
			Object.keys(params["context"]).forEach(function(key) {
				setFields += "'" + key + "'" + "=" + "'" + params["context"][key] + "'" + ','
			})
			setFields = setFields.substring(0, setFields.length - 1) // 去掉最后一个','
			plus.sqlite.executeSql({
				name: DBname,
				sql: `UPDATE ${table_name} SET ${setFields} WHERE ID = ${params.id};`, // 未完成
				success: function(data) {
					console.log(`${table_name}更新成功`);
					resolve(data)
				},
				fail: function(e) {
					console.log(`update ${table_name} fail`)
					reject(e) // 失败回调
				}
			})
		}),
		
		// 删除
		delete: (params) => new Promise((resolve, reject) => {
			let sql
			sql = `DELETE FROM   ${table_name} WHERE `
			Object.keys(params).forEach(function(key) {
				sql = sql + key + '=' + "'" + params[key] + "'" + ' AND'
			})
			sql = sql.substring(0, sql.length - 4); // 去掉最后一个'AND'
			
			plus.sqlite.executeSql({
				name: DBname,
				sql: sql, // 未完成
				success: function(data) {
					console.log(`${table_name}成功`);
					resolve(data)
				},
				fail: function(e) {
					console.log(sql)
					console.log(`DELETE ${table_name} fail`)
					reject(e) // 失败回调
				}
			})
		}),

		// 添加
		insert: (params) => new Promise((resolve, reject) => {
		    let fields = '';
		    let values = '';
		    
		    Object.keys(params).forEach(function(key) {
		        fields += key + ',';
		        
		        let value = params[key];
		        
		        // 如果值是字符串，则需要加上单引号
		        if (typeof value === 'string') {
		            value = `'${value.replace(/'/g, "''")}'`; // 处理单引号，避免 SQL 注入
		        }
		        // 如果是日期，确保格式正确
		        else if (value instanceof Date) {
		            value = `'${value.toISOString().slice(0, 19).replace('T', ' ')}'`; // 转换为 DATETIME 格式
		        }
		
		        values += value + ',';
		    });
		
		    // 去掉最后一个逗号
		    fields = fields.slice(0, -1);
		    values = values.slice(0, -1);
		
		    // 打印检查
		    console.log('fields:', fields);
		    console.log('values:', values);
		
		    // 执行 SQL 插入
		    plus.sqlite.executeSql({
		        name: DBname,
		        sql: `INSERT INTO ${table_name} (${fields}) VALUES (${values})`,
		        success: function(e) {
		            console.log('Insert success!');
		            resolve(e); // Resolve the promise on success
		        },
		        fail: function(e) {
		            console.log('executeSql failed: ' + JSON.stringify(e));
		            reject(e); // Reject the promise on failure
		        }
		    });
		})
	}
}

export {
	localSqliteApi
}
